import 'dart:collection';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:svgaplayer_3/parser.dart';
import 'package:svgaplayer_3/player.dart';

class RoomSvgaQueuePlayer extends StatefulWidget {
  const RoomSvgaQueuePlayer({Key? key}) : super(key: key);

  /// 向全局播放队列添加 SVGA 动画 URL
  @override
  _RoomSvgaQueuePlayerState createState() => _RoomSvgaQueuePlayerState();
}

class _RoomSvgaQueuePlayerState extends State<RoomSvgaQueuePlayer>
    with SingleTickerProviderStateMixin {
  late SVGAAnimationController _controller;

  final Queue<String> _svgaQueue = ListQueue();
  bool _isPlaying = false;
  bool _disposed = false;

  @override
  void initState() {
    super.initState();
    _controller = SVGAAnimationController(vsync: this)
      ..addListener(() {
        if (_controller.isCompleted) {
          _isPlaying = false;
          _playNext();
        }
      });
  }

  void addToQueue(String svgaUrl) {
    _svgaQueue.addLast(svgaUrl);
    _playNext();
  }

  Future<void> _playNext() async {
    if (_isPlaying || _svgaQueue.isEmpty || _disposed) return;

    final url = _svgaQueue.removeFirst();
    _isPlaying = true;

    try {
      final file = await _downloadOrGetCache(url);
      if (_disposed) return;
      final bytes = await file.readAsBytes();
      final videoItem = await SVGAParser.shared.decodeFromBuffer(bytes);
      _controller.videoItem = videoItem;
      if (_disposed) return;
      _controller.repeat(count: 1);
    } catch (e) {
      debugPrint("播放失败: $e");
      _isPlaying = false;
      _playNext(); // 跳过失败的，播放下一个
    }
  }

  /// 下载或从缓存中获取 svga 文件
  Future<File> _downloadOrGetCache(String url) async {
    final fileName = Uri.parse(url).pathSegments.last;
    final dir = await getTemporaryDirectory();
    final filePath = '${dir.path}/$fileName';
    final file = File(filePath);

    if (!await file.exists()) {
      final response = await Dio().get<List<int>>(
        url,
        options: Options(responseType: ResponseType.bytes),
      );
      await file.writeAsBytes(response.data!);
    }
    return file;
  }

  @override
  void dispose() {
    _disposed = true;
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      child: SVGAImage(_controller),
    );
  }
}
